package com.blrs.service.procure.procure.impl;

import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

import com.blrs.common.utils.ReflectionUtils;
import com.blrs.common.utils.SecurityUtils;
import com.blrs.common.utils.StringUtils;
import com.blrs.domain.MainType;
import com.blrs.domain.PurchasingChangeRecord;
import com.blrs.mapper.MainTypeMapper;
import com.blrs.mapper.PurchasingChangeRecordMapper;
import com.blrs.service.procure.procure.IPurchasingService;
import com.blrs.system.mapper.SysDictDataMapper;
import com.blrs.system.mapper.SysUploadFileMapper;
import com.blrs.system.service.ISysDeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.blrs.mapper.PurchasingMapper;
import com.blrs.domain.Purchasing;

/**
 * 采购管理Service业务层处理
 * 
 * @author ruoyi
 * @date 2023-10-17
 */
@Service
public class PurchasingServiceImpl implements IPurchasingService
{
    @Autowired
    private PurchasingMapper purchasingMapper;
    @Autowired
    private SysUploadFileMapper sysUploadFileMapper;
    @Autowired
    private PurchasingChangeRecordMapper purchasingChangeRecordMapper;
    @Autowired
    private MainTypeMapper mainTypeMapper;
    @Autowired
    private SysDictDataMapper sysDictDataMapper;
    @Autowired
    private ISysDeptService sysDeptService;

    /**
     * 查询采购管理
     * 
     * @param id 采购管理主键
     * @return 采购管理
     */
    @Override
    public Purchasing selectPurchasingById(String id)
    {
        Purchasing purchasing = purchasingMapper.selectPurchasingById(id);
        // 获取采购数量
        Integer num = purchasing.getNum();
// 获取单价并转换为BigDecimal类型
        BigDecimal unitPrice = purchasing.getUnitPrice();
// 将Integer类型的数量转换为BigDecimal类型
        BigDecimal numBigDecimal = new BigDecimal(num);
// 计算总价并设置
        purchasing.setTotalPrice(unitPrice.multiply(numBigDecimal));
        return purchasing;
    }

    /**
     * 查询采购管理列表
     * 
     * @param purchasing 采购管理
     * @return 采购管理
     */
    @Override
    public List<Purchasing> selectPurchasingList(Purchasing purchasing)
    {
        purchasing.setOrganizationId(SecurityUtils.getOrgId());
        List<Purchasing> purchasings = purchasingMapper.selectPurchasingList(purchasing);
        for (Purchasing purchasing1 : purchasings) {
            String s = sysUploadFileMapper.selectUrlByCode("procure", purchasing1.getFileUpload());
            if (StringUtils.isNotEmpty(s)){
                purchasing1.setFileUrl(s);
            }
            // 获取采购数量
            Integer num = purchasing1.getNum();
// 获取单价并转换为BigDecimal类型
            BigDecimal unitPrice = purchasing1.getUnitPrice();
// 将Integer类型的数量转换为BigDecimal类型
            BigDecimal numBigDecimal = new BigDecimal(num);
// 计算总价并设置
            purchasing1.setTotalPrice(unitPrice.multiply(numBigDecimal));
        }
        return purchasings;
    }

    @Override
    public List<Purchasing> selectPurchasingListExamine(Purchasing purchasing) {
        List<Purchasing> purchasings = purchasingMapper.selectPurchasingListExamine(purchasing);
        for (Purchasing purchasing1 : purchasings) {
            String s = sysUploadFileMapper.selectUrlByCode("procure", purchasing1.getFileUpload());
            if (StringUtils.isNotEmpty(s)){
                purchasing1.setFileUrl(s);
            }
            // 获取采购数量
            Integer num = purchasing1.getNum();
// 获取单价并转换为BigDecimal类型
            BigDecimal unitPrice = purchasing1.getUnitPrice();
// 将Integer类型的数量转换为BigDecimal类型
            BigDecimal numBigDecimal = new BigDecimal(num);
// 计算总价并设置
            purchasing1.setTotalPrice(unitPrice.multiply(numBigDecimal));
        }
        return purchasings;
    }



    /**
     * 新增采购管理
     * 
     * @param purchasing 采购管理
     * @return 结果
     */
    @Override
    public int insertPurchasing(Purchasing purchasing) throws NoSuchFieldException, IllegalAccessException {
        ReflectionUtils.setCommonPrivateProperty(purchasing);
        purchasing.setOrganizationId(SecurityUtils.getOrgId());
        purchasing.setOrganizationName(SecurityUtils.getOrgName());
        return purchasingMapper.insertPurchasing(purchasing);
    }

    /**
     * 修改采购管理
     * 
     * @param purchasing 采购管理
     * @return 结果
     */
    @Override
    public int updatePurchasing(Purchasing purchasing) throws NoSuchFieldException, IllegalAccessException {
        //先获取原始数据
        Purchasing purchasing1 = purchasingMapper.selectPurchasingById(purchasing.getId());
        //利用反射获取两个对象的差异属性有哪些
        Map<String, String> stringObjectMap = comparePurchasing(purchasing1, purchasing);
         if (stringObjectMap.size()>0) {
             StringBuilder sb = new StringBuilder();
             for (Map.Entry<String, String> entry : stringObjectMap.entrySet()) {
                 String key = entry.getKey();
                 String value = entry.getValue();

                 sb.append(key).append(":").append(value).append(",");
             }

             // 删除最后一个逗号
             if (sb.length() > 0) {
                 sb.deleteCharAt(sb.length() - 1);
             }
             //变更内容
             PurchasingChangeRecord purchasingChangeRecord = new PurchasingChangeRecord();
             purchasingChangeRecord.setPurchasingId(purchasing.getId());
             purchasingChangeRecord.setPurchasingContent(sb.toString());
             purchasingChangeRecord.setPurchasingTime(new Date());
             purchasingChangeRecord.setUserChangedId(SecurityUtils.getUserId());
             purchasingChangeRecord.setUserChanged(SecurityUtils.getUsername());
             purchasingChangeRecord.setId(UUID.randomUUID().toString().replaceAll("-",""));
             purchasingChangeRecordMapper.insertPurchasingChangeRecord(purchasingChangeRecord);
         }
        purchasing.setExamineStatus("已提交");
        return purchasingMapper.updatePurchasing(purchasing);

    }
    @Override
    public int updatePurchasingCooperate(Purchasing purchasing) {
        purchasing.setExamineStatus("已提交");
        return purchasingMapper.updatePurchasing(purchasing);
    }


    /**
     * 判断两个采购管理数据的差异值
     * @param purchasing
     * @param purchasing1
     * @return
     */
    public  Map<String,String> comparePurchasing(Purchasing purchasing, Purchasing purchasing1) throws NoSuchFieldException, IllegalAccessException {
        HashMap<String, String> map = new HashMap<>();
        HashMap<String, Object> changeMap = new HashMap<>();
        Field classificationId = Purchasing.class.getDeclaredField("classificationId");
        Field supplier = Purchasing.class.getDeclaredField("supplier");
        Field enterpriseName = Purchasing.class.getDeclaredField("enterpriseName");
        Field projectNo = Purchasing.class.getDeclaredField("projectNo");
        Field projectName = Purchasing.class.getDeclaredField("projectName");
        Field planTime = Purchasing.class.getDeclaredField("planTime");
        Field completeTime = Purchasing.class.getDeclaredField("completeTime");
        Field fee = Purchasing.class.getDeclaredField("fee");
        Field realityFee = Purchasing.class.getDeclaredField("realityFee");
        Field status = Purchasing.class.getDeclaredField("status");
        Field fileUpload = Purchasing.class.getDeclaredField("fileUpload");
        changeMap.put("主分类",classificationId);
        changeMap.put("供应商",supplier);
        changeMap.put("客户名称",enterpriseName);
        changeMap.put("项目编号",projectNo);
        changeMap.put("项目名称",projectName);
        changeMap.put("计划时间",planTime);
        changeMap.put("完成时间",completeTime);
        changeMap.put("费用",fee);
        changeMap.put("实付费用",realityFee);
        changeMap.put("状态",status);
        changeMap.put("附件",fileUpload);
        for (Map.Entry<String, Object> entry : changeMap.entrySet()) {
            String key = entry.getKey();
            Object value = entry.getValue();
                Field field = (Field) value;
                field.setAccessible(true); // 设置访问权限为可访问
            Object value1 = field.get(purchasing);
            Object value2 = field.get(purchasing1);
            if (key.equals("状态")){
                if (!value1.equals(value2)){
                    String dictName1=sysDictDataMapper.selectDictDataByValueAndType((String)value1,"procure_status");
                    String dictName2=sysDictDataMapper.selectDictDataByValueAndType((String)value2,"procure_status");
                    map.put(key,dictName1+"变更为"+dictName2);
                }
            }
            else if (key.equals("计划时间") || key.equals("完成时间")){
                if (!value1.equals(value2)){
                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                    String format = simpleDateFormat.format((Date) value1);
                    String format1 = simpleDateFormat.format((Date) value2);
                    map.put(key,format+"变更为"+format1);
                }
            }else {
                // 比较属性值是否相等
                if ((value1 != null && value2 != null && !value1.equals(value2)) ) {
                    if (value1 instanceof  BigDecimal){
                        BigDecimal val1=(BigDecimal) value1;
                        BigDecimal val2=(BigDecimal) value2;

//                        //因为在java中 200.00和200的BigDecimal是不一样的，所以需要value2加上尾部的00
//                        val1 = val1.stripTrailingZeros();
//                        val2 = val2.stripTrailingZeros().setScale(val1.scale());
                        if (val1.compareTo(val2)!=0){
                            map.put(key, value1+"变更为"+value2);
                        }
                    } else {
                        map.put(key, value1+"变更为"+value2);
                    }

                }
            }
        }


        return map;
    }

    /**
     * 批量删除采购管理
     * 
     * @param ids 需要删除的采购管理主键
     * @return 结果
     */
    @Override
    public int deletePurchasingByIds(String[] ids)
    {
        return purchasingMapper.deletePurchasingByIds(ids);
    }

    /**
     * 删除采购管理信息
     * 
     * @param id 采购管理主键
     * @return 结果
     */
    @Override
    public int deletePurchasingById(String id)
    {
        return purchasingMapper.deletePurchasingById(id);
    }

    @Override
    public int updatePurchasingStatus(String id) {
        return purchasingMapper.updatePurchasingStatus(id);
    }

    @Override
    public String findLastNo() {
        // 获取当前日期
        LocalDate currentDate = LocalDate.now();
        // 构造查询条件：日期的起始时间和结束时间
        LocalDateTime startTime = currentDate.atStartOfDay();
        LocalDateTime endTime = currentDate.plusDays(1).atStartOfDay();
        // 查询当天已存在的编号数量
        int count = purchasingMapper.countByNumberCreatedBetween(startTime, endTime);
        // 构建新的编号
        return String.format("%s%03d", currentDate.format(DateTimeFormatter.BASIC_ISO_DATE), count + 1);
    }

    @Override
    public int updatePurchasingExamineStatus(String id) {
        return purchasingMapper.updatePurchasingExamineStatus(id);
    }

    @Override
    public int repulse(String id) {
        return purchasingMapper.repulseStatus(id);
    }

    @Override
    public int updatePurchasingByProjectId(Purchasing purchasing) {

        return purchasingMapper.updatePurchasingByProjectId(purchasing);
    }

}
